package com.zq.it.service.impl.exam;

import java.io.File;
import java.util.List;

import com.zq.it.pojo.Teacher;
import com.zq.it.pojo.exam.TCourseWare;
import com.zq.it.service.common.BaseServiceImpl;
import com.zq.it.service.exam.CourseWareService;

public class CourseWareServiceImpl extends BaseServiceImpl
		implements
			CourseWareService {

	@Override
	public void addCourseWare(TCourseWare cware) {
		courseWareDAO.save(cware);
	}

	@Override
	public TCourseWare getCourseWare(Long id) {
		return courseWareDAO.findById(id);
	}

	@Override
	public void deleteCourseWare(Long[] ids, String path, Teacher teacher) {
		String url = null;
		for (long id : ids) {
			TCourseWare courseWare = courseWareDAO.findById(id);
			if (courseWare.getTId() == teacher.getId()) {
				if (courseWare.getType() == 0) {
					url = path + "\\" + "kejian";
				} else if (courseWare.getType() == 1) {
					url = path + "\\readOnline";
				}
				deleteFile(url + "/" + courseWare.getFileName());
				courseWareDAO.delete(courseWare);
			} else {
				throw new RuntimeException("权限不足！");
			}
		}
	}

	@Override
	public void deleteFile(String path) {
		File temp = new File(path);
		if (temp.isFile()) {
			temp.delete();
		}
	}

	@Override
	public List getTeacherByName(String name) {
		return getTeacherDao().findByName(name);
	}

	@Override
	public String createCourseWareHql(TCourseWare courseWare) {
		StringBuffer hql = new StringBuffer(
				"from TCourseWare as model where 1=1");
		String nameSql = courseWare.getName() == null
				|| "".equals(courseWare.getName())
						? ""
						: " and model.name like '%" + courseWare.getName()
								+ "%'";
		String typeSql = "";
		if (courseWare.getType() != -1) {
			typeSql = courseWare.getType() < 0
					? " and model.type=" + courseWare.getType()
					: " and model.type =" + courseWare.getType();
		} else {

		}
		String tIdSql = courseWare.getTId() <= 0
				? ""
				: " and model.TId =" + courseWare.getTId();

		hql.append(nameSql).append(typeSql).append(tIdSql);
		return hql.toString();
	}

	@Override
	public String createStudentHql(TCourseWare courseWare) {
		StringBuffer hql = new StringBuffer(
				"from TCourseWare as model where 1=1");
		String nameSql = courseWare.getName() == null
				|| "".equals(courseWare.getName())
						? ""
						: " and model.name like '%" + courseWare.getName()
								+ "%'";
		String typeSql = "";
		if (courseWare.getType() != -1) {
			typeSql = courseWare.getType() < 0
					? " and model.type=" + courseWare.getType()
					: " and model.type =" + courseWare.getType();
		} else {

		}
		String tIdSql = null;
		if (courseWare.getTId() == -1) {
			tIdSql = " and model.TId =-1";
		} else {
			tIdSql = courseWare.getTId() <= 0
					? ""
					: " and model.TId =" + courseWare.getTId();
		}

		hql.append(nameSql).append(typeSql).append(tIdSql);
		return hql.toString();
	}
}
